package cz.muni.fi.PA165.musiclibraryweb;

import cz.muni.fi.PA165.musiclibraryapi.services.UserService;
import cz.muni.fi.PA165.musiclibrarybackend.dto.UserDTO;
import cz.muni.fi.PA165.musiclibraryweb.signin.SignIn;
import cz.muni.fi.PA165.musiclibraryweb.signin.SignInSession;
import cz.muni.fi.PA165.musiclibraryweb.signin.SignOut;
import cz.muni.fi.PA165.musiclibraryweb.signin.UserRolesAuthorizer;
import cz.muni.fi.PA165.musiclibraryweb.song.SongPage;
import org.apache.wicket.Session;
import org.apache.wicket.authroles.authentication.AbstractAuthenticatedWebSession;
import org.apache.wicket.authroles.authentication.AuthenticatedWebApplication;
import org.apache.wicket.authroles.authorization.strategies.role.RoleAuthorizationStrategy;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Application object for your web application. If you want to run this
 * application without deploying, run the Start class.
 *
 * @see cz.muni.fi.PA165.musiclibaryweb.Start#main(String[])
 */
public class WicketApplication extends AuthenticatedWebApplication {

    /**
     * @see org.apache.wicket.Application#getHomePage()
     */
    @Override
    public Class<? extends WebPage> getHomePage() {
        return SongPage.class;
    }

    /**
     * @see org.apache.wicket.Application#init()
     */
    @Override
    protected void init()
    {
        super.init();
        
        getApplicationSettings().setPageExpiredErrorPage(SignOut.class);
        getApplicationSettings().setAccessDeniedPage(getHomePage());
        
       getSecuritySettings().setAuthorizationStrategy(
            new RoleAuthorizationStrategy(new UserRolesAuthorizer()));
       
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean(UserService.class);
        try {
            UserDTO userDTO = (UserDTO) userService.getUser("admin");   
        }
        catch(Exception e){
            UserDTO userDTO = new UserDTO();
            userDTO.setAdmin(Boolean.TRUE);
            userDTO.setName("admin");
            userDTO.setPassword("admin");
            userService.createUser(userDTO);
        }      
    }

    @Override
    public Session newSession(Request request, Response response) {
        return new SignInSession(request);
    }

    @Override
    protected Class<? extends AbstractAuthenticatedWebSession> getWebSessionClass() {
        return SignInSession.class;
    }

    @Override
    protected Class<? extends WebPage> getSignInPageClass() {
        return SignIn.class;
    }
    
    
}
